import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../providers/payment_history_provider.dart';
import 'model/comic_xxhistory_model.dart';

class CoinHistoryScreen extends ConsumerStatefulWidget {
  const CoinHistoryScreen({super.key});

  @override
  ConsumerState<CoinHistoryScreen> createState() => _CoinHistoryScreenState();
}

class _CoinHistoryScreenState extends ConsumerState<CoinHistoryScreen> {
  // Optimized color constants
  static const Color _primaryBackground = Color(0xFF211839);
  static const Color _secondaryBackground = Color(0xFF2D1F42);
  static const Color _cardBackground = Color(0xFF342952);
  static const Color _borderColor = Color(0xFF4A3B66);
  static const Color _primaryText = Color(0xFFFFFFFF);
  static const Color _secondaryText = Color(0xFFB8B3D1);
  static const Color _tertiaryText = Color(0xFF9B8FB8);
  static const Color _accentPurple = Color(0xFF7C6CE7);
  static const Color _successGreen = Color(0xFF4ECDC4);
  static const Color _warningOrange = Color(0xFFFFB74D);
  static const Color _errorRed = Color(0xFFFF6B6B);
  static const Color _iconTint = Color(0xFF9B8FB8);

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
    // Load initial data
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref
          .read(paymentHistoryProvider.notifier)
          .loadPaymentHistory(isRefresh: true);
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      ref.read(paymentHistoryProvider.notifier).loadMore();
    }
  }

  @override
  Widget build(BuildContext context) {
    final paymentState = ref.watch(paymentHistoryProvider);

    return Scaffold(
      backgroundColor: _primaryBackground,
      appBar: AppBar(
        backgroundColor: _primaryBackground,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: _primaryText),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: const Text(
          'Payment History',
          style: TextStyle(
            color: _primaryText,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
        centerTitle: true,
      ),
      body: RefreshIndicator(
        onRefresh: () => ref.read(paymentHistoryProvider.notifier).refresh(),
        backgroundColor: _cardBackground,
        color: _accentPurple,
        child: paymentState.records.isEmpty && !paymentState.isLoading
            ? _buildEmptyState()
            : _buildHistoryList(paymentState),
      ),
    );
  }

  Widget _buildEmptyState() {
    return ListView(
      children: [
        SizedBox(
          height: MediaQuery.of(context).size.height * 0.7,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 120,
                  height: 120,
                  decoration: BoxDecoration(
                    color: _secondaryBackground,
                    borderRadius: BorderRadius.circular(60),
                    border: Border.all(
                      color: _borderColor,
                      width: 1.5,
                    ),
                    boxShadow: [
                      BoxShadow(
                        color: _accentPurple.withOpacity(0.1),
                        blurRadius: 20,
                        offset: const Offset(0, 8),
                      ),
                    ],
                  ),
                  child: const Icon(
                    Icons.payment,
                    size: 60,
                    color: _iconTint,
                  ),
                ),
                const SizedBox(height: 24),
                const Text(
                  'No Payment History',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.w600,
                    color: _primaryText,
                  ),
                ),
                const SizedBox(height: 8),
                const Text(
                  'Your payment history will appear here',
                  style: TextStyle(
                    fontSize: 14,
                    color: _secondaryText,
                  ),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildHistoryList(PaymentHistoryState state) {
    return ListView.builder(
      controller: _scrollController,
      padding: const EdgeInsets.all(16),
      itemCount: state.records.length + (state.hasMore ? 1 : 0),
      itemBuilder: (context, index) {
        if (index == state.records.length) {
          return _buildLoadMoreIndicator(state.isLoadingMore);
        }
        final record = state.records[index];
        return _buildHistoryItem(record);
      },
    );
  }

  Widget _buildLoadMoreIndicator(bool isLoading) {
    if (!isLoading) return const SizedBox.shrink();

    return Container(
      padding: const EdgeInsets.all(16),
      alignment: Alignment.center,
      child: SizedBox(
        width: 24,
        height: 24,
        child: CircularProgressIndicator(
          strokeWidth: 2,
          valueColor: AlwaysStoppedAnimation<Color>(_accentPurple),
        ),
      ),
    );
  }

  Widget _buildHistoryItem(ComicXxHistoryModel record) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: _cardBackground,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: _borderColor,
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.15),
            blurRadius: 12,
            offset: const Offset(0, 4),
          ),
          BoxShadow(
            color: _accentPurple.withOpacity(0.05),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: Row(
        children: [
          // Transaction type icon
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: _getTransactionColor(record.type).withOpacity(0.15),
              borderRadius: BorderRadius.circular(24),
              border: Border.all(
                color: _getTransactionColor(record.type).withOpacity(0.3),
                width: 1,
              ),
            ),
            child: Icon(
              _getTransactionIcon(record.type),
              color: _getTransactionColor(record.type),
              size: 24,
            ),
          ),
          const SizedBox(width: 16),
          // Transaction info
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      _getTransactionTitle(record.type),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: _primaryText,
                      ),
                    ),
                    const Spacer(),
                    _buildRechargeTypeChip(record.rechargeType),
                  ],
                ),
                const SizedBox(height: 4),
                if (record.rechargeNum != null)
                  Text(
                    '${record.rechargeNum} coins',
                    style: const TextStyle(
                      fontSize: 14,
                      color: _secondaryText,
                    ),
                  ),
                const SizedBox(height: 4),
                Row(
                  children: [
                    Text(
                      _formatDate(record.createTime.toString()),
                      style: const TextStyle(
                        fontSize: 12,
                        color: _tertiaryText,
                      ),
                    ),
                    const Spacer(),
                    if (record.amount != null && record.amount! > 0)
                      Text(
                        '\$${record.amount!.toStringAsFixed(2)}',
                        style: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: _successGreen,
                        ),
                      ),
                  ],
                ),
                if (record.source != null && record.source!.isNotEmpty)
                  Padding(
                    padding: const EdgeInsets.only(top: 4),
                    child: Text(
                      'Source: ${record.source}',
                      style: const TextStyle(
                        fontSize: 12,
                        color: _tertiaryText,
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRechargeTypeChip(int? rechargeType) {
    if (rechargeType == null) return const SizedBox.shrink();

    Color color;
    String text;

    switch (rechargeType) {
      case 1:
        color = _successGreen;
        text = 'Purchase';
        break;
      case 2:
        color = _warningOrange;
        text = 'Bonus';
        break;
      case 3:
        color = _errorRed;
        text = 'Refund';
        break;
      default:
        color = _accentPurple;
        text = 'Other';
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.15),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: color.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 10,
          fontWeight: FontWeight.w600,
          color: color,
        ),
      ),
    );
  }

  IconData _getTransactionIcon(int? type) {
    switch (type) {
      case 1:
        return Icons.add_circle;
      case 2:
        return Icons.card_giftcard;
      case 3:
        return Icons.remove_circle;
      default:
        return Icons.payment;
    }
  }

  Color _getTransactionColor(int? type) {
    switch (type) {
      case 1:
        return _successGreen;
      case 2:
        return _warningOrange;
      case 3:
        return _errorRed;
      default:
        return _accentPurple;
    }
  }

  String _getTransactionTitle(int? type) {
    switch (type) {
      case 1:
        return 'Coin Purchase';
      case 2:
        return 'Bonus Coins';
      case 3:
        return 'Refund';
      default:
        return 'Transaction';
    }
  }

  String _formatDate(String? dateString) {
    if (dateString == null || dateString.isEmpty) return 'Unknown';

    try {
      // 将字符串转换为整数（10位时间戳）
      final timestamp = int.parse(dateString);
      // 10位时间戳需要乘以1000转换为毫秒
      final date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

      // 格式化为 YY-MM-dd hh:mm
      final year = date.year.toString().substring(2); // 取年份后两位
      final month = date.month.toString().padLeft(2, '0');
      final day = date.day.toString().padLeft(2, '0');
      final hour = date.hour.toString().padLeft(2, '0');
      final minute = date.minute.toString().padLeft(2, '0');

      return '$year-$month-$day $hour:$minute';
    } catch (e) {
      return dateString;
    }
  }
}
